<?php
/**
 * 邮件分组控制器类
 * Created by PhpStorm.
 * User: yumao
 * Date: 2017/6/5
 * Time: 16:29
 */

namespace app\controllers\crontab;

use app\components\msgcenter\MsgCenter;
use yii;
use app\models\marketing\MailGroup;
use app\models\marketing\MailSubgroup;
use app\models\marketing\MailSendlist;
use app\components\TemplateMarket;
use yii\data\Pagination;
use app\components\smarty\SmartyNewRenderer;
use app\components\EmailMarket;
use app\models\marketing\MailGroupEmailTypeStatistics;
use app\components\Site;
use app\models\marketing\MailAutoCreate;
use app\models\marketing\EmailCrm;
use app\components\redis\RedisLock;
use app\components\redis\RedisMarketingEmail;
use app\models\Elog;

class 
AddMailGroupNewController extends \app\base\Controller
{
    
    /**
     * 初始化
     */
    public function init()
    {
        yii::$app->db->enableSlaves = false;        // 禁用从库查询，从主库查询数据。
    }
    
    public function rand_keys($length)
    {
        $key = '';
        $pattern='1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
        for($i=0;$i<$length;$i++)
        {
           $randKey = mt_rand(0,35);
           $key .= $pattern{$randKey};    //生成php随机数
        }
        return $key;
    }
        
    private function mergeCartCouponHtml($mailAutoCreateListInfo,$goodsInfoVal,$trackCode,$couponCode,$template_content) {
       
        // 根据site_id获取网站简称
        $siteObj = new Site();
        $webName = $siteObj->getSiteShortNameById($mailAutoCreateListInfo['site_id']);
        $tableName = "user_{$webName}_goods_data";
        $cartGoodsHtml = '';
        
        $cartGoodsInfo =  json_decode($goodsInfoVal['goods_list'],true);
        if (!empty($cartGoodsInfo)) {
            $cartGoodsInfo['goods_price'] = !empty($cartGoodsInfo['goods_price']) ? $cartGoodsInfo['goods_price'] : "";
            $cartGoodsInfo['url_title'] = !empty($cartGoodsInfo['url_title']) ? $cartGoodsInfo['url_title'] : "";
            $cartGoodsInfo['goods_img'] = !empty($cartGoodsInfo['goods_img']) ? $cartGoodsInfo['goods_img'] : "";
            $cartGoodsHtml = $template_content['cart_goods_info'];  
            // 组装相关数据
            $cartGoodsHtml =  str_replace('{url_title}' , $cartGoodsInfo['url_title'].'?'.$trackCode , $cartGoodsHtml);
            $cartGoodsHtml = str_replace('{eo_price}' , "$".$cartGoodsInfo['goods_price'] , $cartGoodsHtml);
            $cartGoodsHtml = str_replace('{goods_img}' , $cartGoodsInfo['goods_img'] , $cartGoodsHtml);
            
            if (!empty($template_content['coupon_code_info']) && !empty($mailAutoCreateListInfo['need_create_coupon_code']) && !empty($goodsInfoVal['goods_state']) && $goodsInfoVal['goods_state'] == 1) {
                $cartGoodsHtml .= $template_content['coupon_code_info'];
                $cartGoodsHtml = str_replace('{coupon_code}' , $couponCode , $cartGoodsHtml);
            }
        }
        return $cartGoodsHtml;
    }
    
    private function mergeCartCouponHtmlIndefinite($mailAutoCreateListInfo,$goodsInfoV,$trackCode,$couponCode,$template_content,$cookieCode) {
         // 根据site_id获取网站简称
        $siteObj = new Site();
        $webName = $siteObj->getSiteShortNameById($mailAutoCreateListInfo['site_id']);
        $tableName = "user_{$webName}_goods_data";
        $cartGoodsHtml = '';
        
        if (!empty($goodsInfoV)) {
            $cartGoodsHtml = $template_content;
            if (empty($goodsInfoV['goods_url'])) {
                $goodsInfoV['goods_url'] = "";
            }
            if (empty($goodsInfoV['goods_img'])) {
                $goodsInfoV['goods_img'] = "";
            }
            if (empty($goodsInfoV['goods_title'])) {
                $goodsInfoV['goods_title'] = "";
            }
            if (strpos($goodsInfoV['goods_url'],'?') === false) {
                $cartGoodsHtml =  str_replace('{goods_url}' , $goodsInfoV['goods_url'].'?'.$trackCode.'&eo='.$cookieCode , $cartGoodsHtml);
            } else {
                $cartGoodsHtml =  str_replace('{goods_url}' , $goodsInfoV['goods_url'].'&'.$trackCode.'&eo='.$cookieCode , $cartGoodsHtml);
            }
            $cartGoodsHtml =  str_replace('{goods_img}' , $goodsInfoV['goods_img'] , $cartGoodsHtml);
            $cartGoodsHtml =  str_replace('{goods_title}' , $goodsInfoV['goods_title'] , $cartGoodsHtml);
        }
        return $cartGoodsHtml;
    }
   
    private function mergeCartCouponHtmlIndefiniteCommon($mailAutoCreateListInfo,$goodsInfoV,$trackCode,$couponCode,$template_content,$flag) {
        
        // 根据site_id获取网站简称
        $siteObj = new Site();
        $webName = $siteObj->getSiteShortNameById($mailAutoCreateListInfo['site_id']);
        $tableName = "user_{$webName}_goods_data";
        $cartGoodsHtml = '';
        if (!empty($goodsInfoV)) {
            $cartGoodsHtml = $template_content;
            if (empty($goodsInfoV['goods_url'])) {
                $goodsInfoV['goods_url'] = "";
            }
            if (empty($goodsInfoV['goods_img'])) {
                $goodsInfoV['goods_img'] = "";
            }
            if (empty($goodsInfoV['goods_title'])) {
                $goodsInfoV['goods_title'] = "";
            }
            if (empty($goodsInfoV['goods_name'])) {
                $goodsInfoV['goods_name'] = "";
            }
            
            // 市场价和销售价
            if (empty($goodsInfoV['shop_price'])) {
                $goodsInfoV['shop_price'] = '';
            }
            if (empty($goodsInfoV['market_price'])) {
                $goodsInfoV['market_price'] = '';
            }
            if (strpos($goodsInfoV['goods_url'],'?') === false) {
                $cartGoodsHtml =  str_replace('{goods_url}' , $goodsInfoV['goods_url'].'?'.$trackCode, $cartGoodsHtml);
            } else {
                $cartGoodsHtml =  str_replace('{goods_url}' , $goodsInfoV['goods_url'].'&'.$trackCode, $cartGoodsHtml);
            }
            if ($flag == 1) {
                $cartGoodsHtml =  str_replace('{goods_img}' , $goodsInfoV['goods_img'] , $cartGoodsHtml);
            } elseif ($flag == 2) {
                $cartGoodsHtml =  str_replace('{goods_name}' , $goodsInfoV['goods_name'] , $cartGoodsHtml);
            } elseif ($flag == 3) {
                $cartGoodsHtml =  str_replace('{shop_price}' , $goodsInfoV['shop_price'] , $cartGoodsHtml);
                 $cartGoodsHtml =  str_replace('{market_price}' , $goodsInfoV['market_price'] , $cartGoodsHtml);
            }
        }
        return $cartGoodsHtml;
    }
    
    private function mergeScanHtml($mailAutoCreateListInfo,$goodsInfoVal,$trackCode,$couponCode,$template_content) {
       
        // 根据site_id获取网站简称
        $siteObj = new Site();
        $webName = $siteObj->getSiteShortNameById($mailAutoCreateListInfo['site_id']);
        $tableName = "user_{$webName}_goods_data";
        $scanGoodsHtml = '';
        $cartGoodsInfo =  json_decode($goodsInfoVal['goods_list'],true);
        if (!empty($cartGoodsInfo)) {
            $scanGoodsHtml = $template_content['scan_goods_info']; 
            $cartGoodsInfo['goods_price'] = !empty($cartGoodsInfo['goods_price']) ? $cartGoodsInfo['goods_price'] : "";
            $cartGoodsInfo['url_title'] = !empty($cartGoodsInfo['url_title']) ? $cartGoodsInfo['url_title'] : "";
            $cartGoodsInfo['goods_img'] = !empty($cartGoodsInfo['goods_img']) ? $cartGoodsInfo['goods_img'] : "";            
            // 组装相关数据
            $scanGoodsHtml =  str_replace('{url_title}' , $cartGoodsInfo['url_title'].'?'.$trackCode , $scanGoodsHtml);
          
            $scanGoodsHtml = str_replace('{eo_price}' , "$".$cartGoodsInfo['goods_price'] , $scanGoodsHtml);
            $scanGoodsHtml = str_replace('{goods_img}' , $cartGoodsInfo['goods_img'] , $scanGoodsHtml);
            $cartGoodsInfo['goods_title'] = !empty($cartGoodsInfo['goods_title']) ? $cartGoodsInfo['goods_title'] : "";
            $scanGoodsHtml = str_replace('{goods_title}' , $cartGoodsInfo['goods_title'] , $scanGoodsHtml);
            
            if (!empty($template_content['coupon_code_info']) && !empty($mailAutoCreateListInfo['need_create_coupon_code'])) {
                $scanGoodsHtml .= $template_content['coupon_code_info'];
                $scanGoodsHtml = str_replace('{coupon_code}' , $couponCode , $scanGoodsHtml);
            }
        }
        return $scanGoodsHtml;
    }
    
    /**
     * yumao
     * 2018-3-21
     * 组装gb新版购物车邮件相关数据
     * @param Arr $mailAutoCreateListInfo
     * @param Arr $goodsInfoVal
     * @param string $trackCode
     * @param string $template_content
     */
    private function mergeEoCartCookieHtml($mailAutoCreateListInfo,$goodsInfoVal,$trackCode,$templateContent) 
    {
       $templateEocartHtml = ""; // 保存组装后内容
       //var_dump($goodsInfoVal['goods_list']);
       $goodsInfoVal['goods_list'] = str_replace(PHP_EOL, '',$goodsInfoVal['goods_list']);
       $cartGoodsInfo =  json_decode($goodsInfoVal['goods_list'],true);
       $cartGoodsHtml = '';
       $cartGoodsHtmlTemp = "";
      
       if (!empty($cartGoodsInfo)) {
           $i = 1;
           foreach ($cartGoodsInfo as $cartGoodsInfoVal) {
               if ($i > 3) { // 购物车邮件中最多三个商品
                   break;
               }
               $cartGoodsHtmlTemp = $templateContent['eocartContentTpl'];
               $goodsTitle = isset($cartGoodsInfoVal['good_title']) ? addslashes($cartGoodsInfoVal['good_title']) : ""; // 标题
               $shopPrice =  isset($cartGoodsInfoVal['shop_price']) ? $cartGoodsInfoVal['shop_price'] : 0;
               if (empty($shopPrice)) { // 价格不存在则不用这一条数据
                   continue;
               }
               $goodsImg = isset($cartGoodsInfoVal['goods_picture']) ? addslashes($cartGoodsInfoVal['goods_picture']) : ""; // 图片地址
               $goodsUrl = isset($cartGoodsInfoVal['goods_link']) ? (strpos($cartGoodsInfoVal['goods_link'], '?') === false ? addslashes($cartGoodsInfoVal['goods_link']).'?'.$trackCode : addslashes($cartGoodsInfoVal['goods_link']).'&'.$trackCode) : "";
               if (!empty($cartGoodsInfoVal['premium_price']) && !empty($cartGoodsInfoVal['cookie_code']) && !empty($goodsUrl)) { // 如果有专享价，则url中要加cookie_code
                   $goodsUrl .= "&eo={$cartGoodsInfoVal['cookie_code']}";
               } 
               
               $cartGoodsHtmlTemp = str_replace('{goods_title}',$goodsTitle, $cartGoodsHtmlTemp); // 标题
               $cartGoodsHtmlTemp = str_replace('{goods_img}',$goodsImg, $cartGoodsHtmlTemp); // 图片地址
               $cartGoodsHtmlTemp = str_replace('{shop_price}',$shopPrice, $cartGoodsHtmlTemp); // 市场价格
               $cartGoodsHtmlTemp = str_replace('{goods_url}',$goodsUrl, $cartGoodsHtmlTemp); // 商品链接
               if ($i<=2) { // 添加分割代码
                   $cartGoodsHtml .= $cartGoodsHtmlTemp . $templateContent['isolation'];
               } else {
                   $cartGoodsHtml .= $cartGoodsHtmlTemp;
               }
               $i++;
           }
           
       }
       return $cartGoodsHtml;
    }
    
    private function mergeCartCookieHtml($mailAutoCreateListInfo,$goodsInfoVal,$trackCode,$cookieCode,$template_content) {
       
        // 根据site_id获取网站简称
        $siteObj = new Site();
        $webName = $siteObj->getSiteShortNameById($mailAutoCreateListInfo['site_id']);
        $tableName = "user_{$webName}_goods_data";
        $cartGoodsHtml = '';
        
        $cartGoodsInfo =  json_decode($goodsInfoVal['goods_list'],true);
        if (!empty($cartGoodsInfo)) {
             $cartGoodsHtml = $template_content['cart_goods_info'];  
             $cartGoodsInfo['url_title'] = isset($cartGoodsInfo['url_title']) ? $cartGoodsInfo['url_title'] : '';
            // 组装相关数据
             if(!empty($cartGoodsInfo['cookie_code']) && $cartGoodsInfo['goods_state'] < 3)
             {
                 $cartGoodsHtml =  str_replace('{url_title}' , $cartGoodsInfo['url_title'].'?'.$trackCode.'&eo='.$cartGoodsInfo['cookie_code'] , $cartGoodsHtml);
             }
             else
             {
                 $cartGoodsHtml =  str_replace('{url_title}' , $cartGoodsInfo['url_title'].'?'.$trackCode , $cartGoodsHtml);
             }
            $cartGoodsHtml = str_replace('{eo_price}' , "$".(isset($cartGoodsInfo['goods_price']) ? $cartGoodsInfo['goods_price'] : 0) , $cartGoodsHtml);
            $cartGoodsHtml = str_replace('{goods_title}' , isset($cartGoodsInfo['goods_title']) ? $cartGoodsInfo['goods_title'] : '' , $cartGoodsHtml);
            if ($cartGoodsInfo['goods_state'] >= 3) {
                $cartGoodsHtml = str_replace('<font style="text-decoration:line-through;">{market_price}</font>','',$cartGoodsHtml);
            } else {
                $cartGoodsHtml = str_replace('{market_price}' , "$".(isset($cartGoodsInfo['market_price']) ? $cartGoodsInfo['market_price'] : 0) , $cartGoodsHtml);
            }
            
            $cartGoodsHtml = str_replace('{goods_img}' , isset($cartGoodsInfo['goods_img']) ? $cartGoodsInfo['goods_img'] : '' , $cartGoodsHtml);
            
        }
        return $cartGoodsHtml;
    }
    
    /**
     * 获取合适条件的用户数据
     */
    private function getData($mailAutoCreateListInfo, $curDayStart = 0)
    {  
        $curTime = \yii::$app->bjTime->time();
        // 发送数据同步时间必须小于当天发送时间点才行
        $curBjTime = \yii::$app->bjTime->time();
        $curDate = \yii::$app->bjTime->date('Y-m-d');
        $curDayStart = $curDayStart ? $curDayStart : \yii::$app->bjTime->strtotime($curDate." 00:00:00"); // 当天0时0分0秒时间戳
       
        $curAutoCreateSendTimeCurDay = $curDayStart + $mailAutoCreateListInfo['plan_send_time'];
        
        // 根据site_id获取网站简称
        $siteObj = new Site();
        $siteShortName = $siteObj->getSiteShortNameById($mailAutoCreateListInfo['site_id']);
        
        // 公共过滤条件
        $commonWhere = "";
        $commonWhere .= ' u.is_complaint=0';   //没有被投诉
        $commonWhere .= ' and u.is_received_promo = 1  and u.is_block=0 and u.is_bound=0';   //没退订,黑名单,硬弹
        
        /******* 根据排除条件过滤掉一些数据start *******/
        // 排除掉最近几天有发过所有邮件的
        if (!empty($mailAutoCreateListInfo['filter_all_email_day']) && is_numeric($mailAutoCreateListInfo['filter_all_email_day'])) {
            if (!empty($mailAutoCreateListInfo['is_old'])) {
                if (!empty($mailAutoCreateListInfo['user_email_type'])) { // 旧edm新版数据
                    $updateSqlFilterAllEmail = "update user_{$siteShortName}_goods_data as cg,user_{$siteShortName} as u set cg.send_state=2 where cg.site_user_id = u.site_user_id and cg.user_email_type = {$mailAutoCreateListInfo['user_email_type']} and cg.send_state=0 and u.last_sent_time > " . ($curTime - $mailAutoCreateListInfo['filter_all_email_day'] * 24 * 3600);
                } elseif (!empty($mailAutoCreateListInfo['goods_type'])) { // 旧edm旧版数据
                    $updateSqlFilterAllEmail = "update user_{$siteShortName}_goods_data as cg,user_{$siteShortName} as u set cg.send_state=2 where cg.site_user_id = u.site_user_id and cg.goods_type = {$mailAutoCreateListInfo['goods_type']} and cg.send_state=0 and u.last_sent_time > " . ($curTime - $mailAutoCreateListInfo['filter_all_email_day'] * 24 * 3600);
                }
            } else {
                $updateSqlFilterAllEmail = "update user_{$siteShortName}_goods_data as cg,user_{$siteShortName} as u set cg.send_state=2 where cg.site_user_id = u.site_user_id and cg.auto_create_id = {$mailAutoCreateListInfo['id']} and cg.send_state=0 and u.last_sent_time > " . ($curTime - $mailAutoCreateListInfo['filter_all_email_day'] * 24 * 3600);
            }
            yii::$app->db->createCommand($updateSqlFilterAllEmail)->execute();  
        }
        
        // gb 新版soa浏览记录要排除28天之内没有打开邮件的用户
        if (!empty($mailAutoCreateListInfo['site_id']) && $mailAutoCreateListInfo['site_id'] == 12
                && !empty($mailAutoCreateListInfo['user_email_type']) && $mailAutoCreateListInfo['user_email_type'] == 14) {
            $updateSqlFilterOpen = "update user_{$siteShortName}_goods_data as cg,user_{$siteShortName} as u set cg.send_state=2 where cg.site_user_id = u.site_user_id "
            . " and cg.user_email_type = 14 and u.last_open < " . ($curBjTime - 28*24*3600);
             yii::$app->db->createCommand($updateSqlFilterOpen)->execute();  
        }
       
        if (!empty($mailAutoCreateListInfo['filter_con'])) {
            $filterWhereArr = [];
            $filterWhere = ""; // 过滤的相关条件
            $groupIdArr = []; // 分组id
            $groupIdArrTmp = []; // 分组id
            $filterConArr = json_decode($mailAutoCreateListInfo['filter_con'],true);
            
            foreach ($filterConArr as $filterConVal) {
                
                // 根据模版id找到队列表中发送过邮件的数据
                $timeEnd = $curTime - $filterConVal['delay'] * 24 * 3600;
                $filterWhereArr[] = " (template_id = {$filterConVal['template_id']} and add_date > {$timeEnd}) "; 
            }
            
            if (!empty($filterWhereArr)) {
                $filterWhere = join(' or ',$filterWhereArr);
                
                // 查询相关分组id值
                $sql = " select group_id from mail_group where {$filterWhere} ";
                $groupIdArrTmp = yii::$app->db->createCommand($sql)->queryAll();
                
                if (!empty($groupIdArrTmp)) {
                    foreach ($groupIdArrTmp as $groupIdArrTmpV) {
                        $groupIdArr[] = $groupIdArrTmpV['group_id'];   
                    }
                }
                
                // 把相关分组有发送过的用户的状态改成2（表示不符合条件）
                if (!empty($groupIdArr)) {
                    $groupIdStr = join(",",$groupIdArr);
                    
                    foreach ($groupIdArr as $groupIdArrVal) {
                        $tableNameSendlist = MailSendlist::getInstance()->getTableName($mailAutoCreateListInfo['site_id'], $groupIdArrVal);
                        if (!empty($mailAutoCreateListInfo['is_old'])) {
                            if (!empty($mailAutoCreateListInfo['user_email_type'])) { // 旧edm新版数据
                                $updateSql = " update user_{$siteShortName}_goods_data as cg,{$tableNameSendlist} as ms "
                                . " set cg.send_state=2 where cg.site_user_id = ms.site_user_id and cg.user_email_type = {$mailAutoCreateListInfo['user_email_type']} "
                                . " and cg.send_state=0 and ms.group_id = {$groupIdArrVal}";   
                            } elseif (!empty($mailAutoCreateListInfo['goods_type'])) { // 旧edm旧版数据
                                $updateSql = " update user_{$siteShortName}_goods_data as cg,{$tableNameSendlist} as ms "
                                . " set cg.send_state=2 where cg.site_user_id = ms.site_user_id and cg.goods_type = {$mailAutoCreateListInfo['goods_type']} "
                                . " and cg.send_state=0 and ms.group_id = {$groupIdArrVal}";  
                            }   
                        } else { // 新的emp的数据
                            $updateSql = " update user_{$siteShortName}_goods_data as cg,{$tableNameSendlist} as ms "
                            . " set cg.send_state=2 where cg.site_user_id = ms.site_user_id and cg.auto_create_id = {$mailAutoCreateListInfo['id']} "
                            . " and cg.send_state=0 and  ms.group_id = {$groupIdArrVal}";
                        }

                        // 更新相关数据
                        if (!empty($updateSql)) {
                            yii::$app->db->createCommand($updateSql)->execute();  
                        } 
                    }
                }
            }
        }
        
        
        /******* 根据排除条件过滤掉一些数据end *******/

        /************** 查询相关数据开始 *************/
        $where = ' cg.send_state = 0 ';
        
        // 如果有其他订阅过滤则也要加上相关条件
        $otherReceivedWhere = "";
        if (!empty($mailAutoCreateListInfo['must_received'])) { // 说明有其他相关条件
            $mustReceived = json_decode($mailAutoCreateListInfo['must_received'],true);
            $params = [];
            $i=1;
            $otherReceivedWhereArr = [];
            $otherReceivedWhereTmp = "";
            foreach ($mustReceived as $mustReceivedVal) {
                $params[':mustReceivedKey'.$i] = '%"' . $mustReceivedVal . '"%';
                $otherReceivedWhereArr[] = " u.is_not_received_custom_promo_json not like :mustReceivedKey{$i}";
            }
            if (!empty($otherReceivedWhereArr)) {
                $otherReceivedWhereTmp = join(" and " , $otherReceivedWhereArr);
                $otherReceivedWhere = " ( {$otherReceivedWhereTmp} )";
            }  
        }

        // 兼容旧版的相关数据
        if (!empty($mailAutoCreateListInfo['is_old'])) {
            if (!empty($mailAutoCreateListInfo['user_email_type'])) {// 旧edm新版数据(用user_email_type来判断要发送的邮件类型)
                $where .= " and cg.user_email_type = {$mailAutoCreateListInfo['user_email_type']} " ;
            } elseif (!empty($mailAutoCreateListInfo['goods_type'])) { // 旧edm旧版数据(用goods_type来判断要发送的邮件类型)
                $where .= " and cg.goods_type = {$mailAutoCreateListInfo['goods_type']} " ;
            } else { // 说明数据记录有问题
                $where .= " and 1 = 2 ";
            }
        } else { // 新的emp的数据
            $where .= " and cg.auto_create_id = {$mailAutoCreateListInfo['id']} " ;
        }
        
        // 从 send_mode_id 来判断发送方式 0代表网站推送数据当日发送，1以网站推送时间延后发送，2以用户加购时间延后发送
        if ($mailAutoCreateListInfo['send_mode_id'] == 0) { // 代表网站推送数据当日发送
            // $where .= ' and create_time >= ' . ($curTime-24*3600);
            $where .= ' and create_time >= ' . ($curAutoCreateSendTimeCurDay-24*3600); 
        } elseif($mailAutoCreateListInfo['send_mode_id'] == 1) { // 以网站推送时间延后发送
            $where .= ' and create_time < ' . ($curAutoCreateSendTimeCurDay-$mailAutoCreateListInfo['delay_day'] * 24*3600) .' and create_time >= ' . ($curAutoCreateSendTimeCurDay-($mailAutoCreateListInfo['delay_day']+1) * 24*3600);
        } elseif($mailAutoCreateListInfo['send_mode_id'] == 2) { // 以用户加购时间延后发送
            if ($mailAutoCreateListInfo['site_id'] == 22) { // gamiss是按照天来算
                $daysAgo = \yii::$app->bjTime->date("Y-m-d",$curDayStart - $mailAutoCreateListInfo['delay_day'] * 24*3600);
                $stime = \yii::$app->bjTime->strtotime($daysAgo." 00:00:00");
                $etime = \yii::$app->bjTime->strtotime($daysAgo." 23:59:59");
                $where .= ' and add_cart_time < ' . $etime .' and add_cart_time >= ' . $stime;
            } else {
                $where .= ' and add_cart_time < ' . ($curAutoCreateSendTimeCurDay-$mailAutoCreateListInfo['delay_day'] * 24*3600) .' and add_cart_time >= ' . ($curAutoCreateSendTimeCurDay-($mailAutoCreateListInfo['delay_day']+1) * 24*3600);
            }
        }
        $where .= ' and create_time <= ' . $curAutoCreateSendTimeCurDay;
        
        // 筛选国家用户数据
        if(!empty($mailAutoCreateListInfo['select_region_condition'])) {
            $selectRegionInfo = json_decode($mailAutoCreateListInfo['select_region_condition'], true);
            if($selectRegionInfo) {
                $where .= " and u.region_code in (\"".join('","',$selectRegionInfo)."\")";
            }
        }
        
        // 过滤国家用户数据
        if(!empty($mailAutoCreateListInfo['filter_region_condition'])) {
            $filterRegionInfo = json_decode($mailAutoCreateListInfo['filter_region_condition'], true);
            if($filterRegionInfo) {
                $where .= " and u.region_code not in (\"".join('","',$filterRegionInfo)."\")"; 
            }
            
        }
        
        // 组装sql语句
        if (!empty($otherReceivedWhere)) {
            $selectUserSql = "select u.user_id,cg.id from user_{$siteShortName}_goods_data as cg join user_{$siteShortName} as u on cg.site_user_id = u.site_user_id where {$commonWhere} and {$otherReceivedWhere} and {$where} ";
        } else {
            $selectUserSql = "select u.user_id,cg.id from user_{$siteShortName}_goods_data as cg join user_{$siteShortName} as u on cg.site_user_id = u.site_user_id where {$commonWhere} and {$where} ";
        }
//        var_dump($selectUserSql);exit;
        if (isset($selectUserSql)) {
            if (!empty($otherReceivedWhere)) {
                $userIdArr = yii::$app->db->createCommand($selectUserSql)->bindValues($params)->queryAll();
            } else {
                $userIdArr = yii::$app->db->createCommand($selectUserSql)->queryAll();
            }
            return $userIdArr;
        } else {
            return false;
        }
        /************** 查询相关数据结束 *************/
    }

    /**
     * yumao
     * 2018-2-27
     * S、TD、TG营销邮件自动化应用方案
     *
     * /crontab/add-mail-group-new/add-group-goods?module_name=marketing_email&site=trendsgal
     *
     */
    public function actionAddGroupGoods()
    {
        set_time_limit(0);
        $siteArr = ['sammydress', 'trendsgal', 'twinkledeals']; // 定义可能用这种方式的网站

        //S、TG、TD
        $lastOrderTime = strtotime("-160 day");
        $lastLogin = strtotime("-1 month");
        $lastRegion = strtotime("-1 month");
        $lastOrderTimeGroup2 = strtotime("-161 day");
        $startOrderTimeGroup2 = strtotime("-365 day");
        $whereArrStr = [
            'sammydress' => "((user.reg_time > 0 and last_order_time >= {$lastOrderTime}) or (last_login >= {$lastLogin}) or (user.reg_time >= {$lastRegion}))" . " and !(is_test = '1' or is_block = '1' or is_bound = '1' or is_complaint = '1' or is_received_promo = '2' or is_received_promo = 0 )",
            'trendsgal' => "((user.reg_time > 0 and last_order_time >= {$lastOrderTime}) or (last_login >= {$lastLogin}) or (user.reg_time >= {$lastRegion}))" . " and !(is_test = '1' or is_block = '1' or is_bound = '1' or is_complaint = '1' or is_received_promo = '2' or is_received_promo = 0 )",
            'twinkledeals' => "((user.reg_time > 0 and last_order_time >= {$lastOrderTime}) or (last_login >= {$lastLogin}) or (user.reg_time >= {$lastRegion}))" . " and !(is_test = '1' or is_block = '1' or is_bound = '1' or is_complaint = '1' or is_received_promo = '2' or is_received_promo = 0 )"
        ]; // 定义查询条件
        $whereArrStr2 = [
            'sammydress' => "(user.reg_time > 0 and last_order_time >= {$startOrderTimeGroup2} and last_order_time < {$lastOrderTimeGroup2})" . " and !(is_test = '1' or is_block = '1'"
                    . " or is_bound = '1' or is_complaint = '1' or is_received_promo = '2' or is_received_promo = 0 or user.reg_time > {$lastRegion} or user.last_login > {$lastLogin})",
            'trendsgal' => "(user.reg_time > 0 and last_order_time >= {$startOrderTimeGroup2} and last_order_time < {$lastOrderTimeGroup2})" . " and !(is_test = '1' or is_block = '1'"
                    . " or is_bound = '1' or is_complaint = '1' or is_received_promo = '2' or is_received_promo = 0 or user.reg_time > {$lastRegion} or user.last_login > {$lastLogin})",
           // 'twinkledeals' => "((user.reg_time > 0 and last_order_time >= {$lastOrderTime}) or (last_login >= {$lastLogin}))" . " and !(is_test = '1' or is_block = '1' or is_bound = '1' or is_complaint = '1' or is_received_promo = '2' or is_received_promo = 0 )"
        ]; // 定义查询条件
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('deal_site_name');
        $groupType = Yii::$app->request->$mothod('group_type');
        
        if (!$site || !in_array($site, $siteArr)) {
            echo 'site is error';
        } else {
            $lastGroup1Key = "last_group1_key";
            $lastGroup2Key = "last_group2_key";
            $redisMarketingEmail = new RedisMarketingEmail($site);
            // 创建分组
            if (!empty($groupType) && $groupType == 2) {
                if (!empty($whereArrStr2[$site])) {
                    try {
                        // 查看上一次发送group2邮件时间
                        $lastSendDay = $redisMarketingEmail->hget($lastGroup2Key,"send_day"); 
                        // 查看上一次发送的group1的分组id值(这个需要排除)
                        $lastSendGroup1Id = $redisMarketingEmail->hget($lastGroup1Key,"group_id");
                        if (empty($lastSendGroup1Id)) {
                            $lastSendGroup1Id = 0;
                        }
                        if (!empty($lastSendDay)) { // 说明有发过这种邮件
                            // 查看有没有经过十天
                            $lastSendDayStartTime = \yii::$app->bjTime->strtotime($lastSendDay . " 00:00:00 "); 
                            
                            // 当天开始时间
                            $curDayStartTime = \yii::$app->bjTime->strtotime(\yii::$app->bjTime->date("Y-m-d") . " 00:00:00 ");
                            
                            // 两个时间点差距有没有10天
                            if ($curDayStartTime - $lastSendDayStartTime < 10*24*60*60 ) { // 不可以发邮件
                                echo '今天不是发送日期!';
                                exit;
                            } 
                        } else { // 没有发送过，查看今天是不是周三
                            $weekNums = \yii::$app->bjTime->date('w');
                            if ($weekNums != 3) {
                                echo '今天不是发送日期!';
                                exit;
                            }
                        }
                        // 发邮件相关
                        $whereStr = $whereArrStr2[$site];
                        $groupId = $this->doAddGroupGoods($site, $whereStr,$lastSendGroup1Id,2);
                        // 把相关数据写入redis中
                        $curDay = \yii::$app->bjTime->date("Y-m-d");
                        $redisMarketingEmail->hset($lastGroup2Key,'send_day',$curDay);
                        $redisMarketingEmail->hset($lastGroup2Key,'group_id',$groupId);
                    } catch (\Exception $ex) {
                        $msg = "自动营销邮件用户分组2创建过程有问题：" . $ex->getMessage();
                        Elog::logCrontab($msg,__FUNCTION__,'exception');
                        echo $msg;
                    }
                } else {
                    echo "当前网站暂不支持此种邮件";
                }
            } else {
                try {
                    $whereStr = $whereArrStr[$site];
                    // 查看上一次发送的group2的分组id值(这个需要排除)
                    $lastSendGroup2Id = $redisMarketingEmail->hget($lastGroup2Key,"group_id");
                    if (empty($lastSendGroup2Id)) {
                        $lastSendGroup2Id = 0;
                    } 
                    $groupId = $this->doAddGroupGoods($site, $whereStr,$lastSendGroup2Id);
                   
                    $redisMarketingEmail->hset($lastGroup1Key,'group_id',$groupId);
                } catch (\Exception $ex) {
                    $msg = "自动营销邮件用户分组1创建过程有问题：" . $ex->getMessage();
                    Elog::logCrontab($msg,__FUNCTION__,'exception');
                    echo $msg;    
                }
            }
        }
    }
    
    /**
     * yumao
     * 添加发送分组
     */
    public function actionAddGroup()
    {
        ignore_user_abort(true); 
        set_time_limit(0);
        $siteObj = new Site();
        $mailAutoCreate = new MailAutoCreate();
        $mothod = strtolower(Yii::$app->request->getMethod());
        $site = Yii::$app->request->$mothod('site');
        $formData = Yii::$app->request->$mothod();

        // 查询未删除的并且启动自动触发邮件任务5个
        if(!empty($_GET['id'])) {
            $id = intval($_GET['id']);
            $mailAutoCreateList = $mailAutoCreate->getAutoCreateListSuit($id);
        } else {
            $mailAutoCreateList = $mailAutoCreate->getAutoCreateListSuit();
        }
        foreach ($mailAutoCreateList as $mailAutoCreateListInfo) {
            echo "开始处理 ".$mailAutoCreateListInfo['id']."\n";
            $curBjTime = \yii::$app->bjTime->time();
            $curDate = \yii::$app->bjTime->date('Y-m-d');
            $curDayStart = \yii::$app->bjTime->strtotime($curDate." 00:00:00");
            $data = [];
            $data['module_name'] = "marketing_email";
           
            if($curBjTime < $curDayStart+$mailAutoCreateListInfo['plan_send_time']) {
                $curDayStart = $curDayStart - 24*60*60;
            }
            // 查看是否到已经添加队列的时间
            if ($curBjTime - $curDayStart >= $mailAutoCreateListInfo['plan_send_time'] || !empty($formData['is_test'])) {   // 说明已经到了生成分组时间
                
                // 获取数据并过滤掉数据
                $userIdArr = $this->getData($mailAutoCreateListInfo, $curDayStart);
               
                // 生成分组
                if (!empty($userIdArr)) {
                    echo "获取到数据，等待生成分组\n";
                    $this->doAddGroup($mailAutoCreateListInfo,$userIdArr,$curDayStart);
                } else {
                    echo "没有获取到数据，跳过分组\n";
                    continue;
                } 
            }else{
                echo $mailAutoCreateListInfo['id']."没有到添加到队列时间";
            }
            sleep(1);
        }  
    }
    
    /*
    *	功能：得到热卖相关商品信息
    */
    private function get_eo_hot_goods( $site_id) {
        
//            date_default_timezone_set('America/Chicago');
            $webName = Yii::$app->params['sites']['marketing_email']['web_index'][$site_id];
            $curTime = \yii::$app->bjTime->time();
            
//            $today_date = date("Y-m-d",\yii::$app->bjTime->time());
//            $ts_time = strtotime($today_date." 00:00:00");
//            $te_time = strtotime($today_date." 23:59:59");
            if ( in_array($site_id, array(17,3)) ) {
                    $sql = " SELECT * FROM user_{$webName}_goods_data WHERE add_cart_time >= ".($curTime-24*3600)." AND add_cart_time <= $curTime AND goods_type =2 " ;
                    $hot_goods = yii::$app->db->createCommand($sql)->queryAll();
            }
            return $hot_goods;
    }
    
    /*
    *	功能：得到购物车相关商品
    */
    private function get_cart_goods($mailAutoCreateListInfo,$site_user_id) {
//            date_default_timezone_set('America/Chicago');
            $curTime = \yii::$app->bjTime->time();
            $webName = Yii::$app->params['sites']['marketing_email']['web_index'][$mailAutoCreateListInfo['site_id']];
//            $three_day_ago = date("Y-m-d",strtotime('-3 day'));
//            $s_time = strtotime($three_day_ago." 00:00:00");
//            $e_time = strtotime($three_day_ago." 23:59:59");

            if ( in_array($mailAutoCreateListInfo['site_id'], array(17,3)) ) {
                    $cart_goods_sql = " SELECT * FROM user_{$webName}_goods_data WHERE add_cart_time > ".($curTime-($mailAutoCreateListInfo['delay_day']+1) * 24*3600)." AND add_cart_time < ".($curTime-$mailAutoCreateListInfo['delay_day'] * 24*3600)." 
                                            AND site_user_id = {$site_user_id} AND goods_type = 1 ORDER BY add_cart_time DESC LIMIT 3";

            }
            $cart_goods = yii::$app->db->createCommand($cart_goods_sql)->queryAll();
            return $cart_goods;

    }
    
    /*
     * 获取每个用户对应的购物车商品和热卖商品
     */
    private function getGoodsInfo($mailAutoCreateListInfo,$site_user_id,$all_hot_goods,$trackCode,$cookieCode,$template_content)
    {
        $cart_goods = $this->get_cart_goods( $mailAutoCreateListInfo,$site_user_id);
        
	if (in_array($mailAutoCreateListInfo['site_id'], array(17,3))) {
		$cat_id_arr = array();
		foreach ($cart_goods as $k => $v ) {
                        $goods_info = json_decode(stripslashes($v['goods_list']),true);
                        if(isset($goods_info['cat_id'])){
                            $cat_id_arr[] = $goods_info['cat_id'];
                        }
		}
		$unique_cat_id_arr = array_unique($cat_id_arr);
		$user_hot_goods = array();
		//得到每个用户对应的热卖
		foreach ($all_hot_goods as $key => $val) {
                        $hot_goods_info = json_decode(stripslashes($val['goods_list']),true);
                        
			foreach ($unique_cat_id_arr as $i => $cat_id) {
				if ( isset($hot_goods_info['cat_id']) && $cat_id == $hot_goods_info['cat_id']) {
					$user_hot_goods[$hot_goods_info['cat_id']][] = $val;
				}
			}
		}
		
	}
       
	$goods_html = $this->merge_zaful_template($mailAutoCreateListInfo['site_id'],$cart_goods,$user_hot_goods,$template_content,$trackCode,$cookieCode);
        
	return $goods_html;

    }
    
    /**
    * @param array
    * @param array
    * $cart_goods   购物车商品信息
    * $hot_goods    热卖商品信息
    *
    */
    private function merge_zaful_template($site_id,$cart_goods,$hot_goods,$template_content,$track_code,$cookieCode) {
            
            $cart_goods_html = '';
            $hot_goods_html = '';
            $track_code = "?".$track_code;
            if ( !empty($cart_goods) ) {    //购物车html
                    $cart_goods_count = count($cart_goods);
                    //var_dump($cart_goods);
                    foreach ( $cart_goods as $key => $val ) {
                            $val = json_decode(stripslashes($val['goods_list']),true);
                            $eo_track_code = $track_code."&eo=".$cookieCode;
                            $cart_goods_html .= $template_content['before_space'];
                            $cart_goods_html .= str_replace('{url_title}', (isset($val['url_title']) ? $val['url_title'] : '').$eo_track_code, $template_content['cart_goods_info']);
                            $cart_goods_html = str_replace('{goods_img}', isset($val['goods_img']) ? $val['goods_img'] : '', $cart_goods_html);
                            $cart_goods_html = str_replace('{goods_title}', isset($val['goods_title']) ? $val['goods_title'] : '', $cart_goods_html);
                            $cart_goods_html = str_replace('{size}', isset($val['size']) ? $val['size'] : '', $cart_goods_html);
                            $cart_goods_html = str_replace('{color}', isset($val['color']) ? $val['color'] : '', $cart_goods_html);
                            $cart_goods_html = str_replace('{eo_price}', "$".(isset($val['goods_price']) ? $val['goods_price'] : 0), $cart_goods_html);
                            if ( $key < $cart_goods_count -1 ) {
                                $cart_goods_html .= $template_content['after_space'];
                            }
                     }
             }
             
             if ( !empty($hot_goods) ) {     //热卖html
                     $hot_goods_html = '';
                     foreach ( $hot_goods as $cat => $goods ) {
                             $hot_goods_html .= "<tr>";
                             foreach ( $goods as $k => $v ) {
                                    $v = json_decode(stripslashes($v['goods_list']),true);
                                     $hot_goods_html .= str_replace('{url_title}', (isset($v['url_title']) ? $v['url_title'] : '').$track_code, $template_content['hot_goods_info']);
                                     $hot_goods_html = str_replace('{goods_img}', isset($v['goods_img']) ? $v['goods_img'] : '', $hot_goods_html);
                                    $hot_goods_html = str_replace('{eo_price}', "$".(isset($v['goods_price']) ? $v['goods_price'] : 0), $hot_goods_html);
                             }
                             $hot_goods_html .= "</tr>";
                     }
             }
             return array('cart_goods_info' => $cart_goods_html,'hot_goods_info' => $hot_goods_html);

     }
    
     /**
     * 更改表中数据状态
     */
    private function updateData($mailAutoCreateListInfo,$haveAddIdArr,$trackCode,$curDayStart=0) {
        $webName = Yii::$app->params['sites']['marketing_email']['web_index'][$mailAutoCreateListInfo['site_id']];
        
        $haveAddIdStr = join(',',$haveAddIdArr);
        
        // 查询user_{$webName}_goods_data表中的相关数据
        $getGoodsInfoSql = " select * from user_{$webName}_goods_data where id in ({$haveAddIdStr}) ";
        
        $goodsInfoArr =  yii::$app->db->createCommand($getGoodsInfoSql)->queryAll();
        
        
        // 定义其它变量的一些默认数据（标准的一个模版）(可能以后还要添加)
        $otherValTpl = [];
        $otherValTpl['nick_name'] = "";
        $otherValTpl['firstname'] = "";
        $otherValTpl['cat_name'] = "";
        $otherValTpl['cat_url'] = "";
        $otherValTpl['cookie_code'] = "";
        $otherValTpl['coupon_code'] = "";
        $otherValTpl['cart_goods_info'] = "";
        $otherValTpl['cart_goods_info_common'] = "";
        $otherValTpl['hot_goods_info'] = "";
        $otherValTpl['scan_goods_info'] = "";
        $otherValTpl['img_info_all'] = "";
        $otherValTpl['goods_name_info_all'] = "";
        $otherValTpl['price_info_all'] = "";
        $otherValTmp['eocart_goods_info'] = ""; // 新加的soa购物车相关
        //$otherValTmp['eoview_new_goods_info'] = ""; // 新加的soa浏览记录相关
        
        if($mailAutoCreateListInfo['is_old'] == 2)
        {
            for ($i=1;$i<=8;$i++) {
                $otherValTpl['goods_url'.$i] = "";
                $otherValTpl['goods_img'.$i] = "";
                $otherValTpl['goods_name'.$i] = ""; 
                $otherValTpl['goods_title'.$i] = ""; 
                $otherValTpl['market_price'.$i] = "";
                $otherValTpl['shop_price'.$i] = "";
                
            }
        }
        //获取hot商品
        if(in_array($mailAutoCreateListInfo['site_id'],[17,3]))
        {
            $all_hot_goods = $this->get_eo_hot_goods($mailAutoCreateListInfo['site_id']);
//            
//            $msg = "自动触发邮件id为{$mailAutoCreateListInfo['id']}获取热门商品：".PHP_EOL.var_export($all_hot_goods,1);
//            $this->writeLog($msg);
        }
       
        foreach ($goodsInfoArr as $goodsInfoKey => $goodsInfoVal) {
            
            // 组装其他变量相关
            $otherValTmp = $otherValTpl;
            
            if(!empty($goodsInfoVal['coupon_code']))
            {
                $otherValTmp['coupon_code'] = $goodsInfoVal['coupon_code'];
            }
            if(!empty($goodsInfoVal['cookie_code']))
            {
                $otherValTmp['cookie_code'] = $goodsInfoVal['cookie_code'];
            }
            // 判断当前分组是否要生成coupon码
            if ($mailAutoCreateListInfo['need_create_coupon_code'] == 1) {
                
                // 生成coupon码
                $couponCode = $this->rand_keys(4);
                
                $otherValTmp['coupon_code'] = $couponCode;
            } 
            
            // 判断是否需要生成cookie码
            if ($mailAutoCreateListInfo['need_create_cookie_code'] == 1) {
                
                // 生成cookie码
                $cookieCode = $this->rand_keys(16);
                $otherValTmp['cookie_code'] = $cookieCode;
            }
            
            // 一些变量替换
            if (!empty($goodsInfoVal['cat_url'])) {
                $catUrl = str_replace("https://" , "", $goodsInfoVal['cat_url']);
                $otherValTmp['cat_url'] = str_replace("http://" , "", $catUrl);  
            }
            
            if (!empty($goodsInfoVal['cat_name'])) {
                $otherValTmp['cat_name'] = $goodsInfoVal['cat_name'];  
            }
            
            if (!empty($goodsInfoVal['firstname'])) {
                $otherValTmp['nick_name'] = $goodsInfoVal['firstname'];  
                $otherValTmp['firstname'] = $goodsInfoVal['firstname'];  
            }
            if ($mailAutoCreateListInfo['is_old'] == 1) { // 旧版edm原来的
            
                // 模版中的一些变量替换
                if(in_array($mailAutoCreateListInfo['site_id'],[17,3]))
                {
                    if (file_exists(ROOT_PATH."/template/{$webName}_template.php")) {
                        include_once(ROOT_PATH."/template/{$webName}_template.php");
                        $goods_html = $this->getGoodsInfo($mailAutoCreateListInfo,$goodsInfoVal['site_user_id'],$all_hot_goods,$trackCode,$cookieCode,$template_content);
                        
                        $otherValTmp['cart_goods_info'] = $goods_html['cart_goods_info'];
                        $otherValTmp['hot_goods_info'] = $goods_html['hot_goods_info'];
                       
                    }
                } else if(in_array($mailAutoCreateListInfo['site_id'],[10])){
                    if (file_exists(ROOT_PATH."/template/{$webName}_template.php")) {
                        include_once(ROOT_PATH."/template/{$webName}_template.php");
                        $template_replace_html = $this->mergeCartCookieHtml($mailAutoCreateListInfo,$goodsInfoVal,$trackCode,$otherValTmp['cookie_code'],$template_content);
                        if (!empty($template_replace_html)) {
                            $otherValTmp['cart_goods_info'] = $template_replace_html;
                        }
                    }
                } else {
                    if (file_exists(ROOT_PATH."/template/{$webName}_template.php")) {
                        include_once(ROOT_PATH."/template/{$webName}_template.php");
                        $template_replace_html = $this->mergeCartCouponHtml($mailAutoCreateListInfo,$goodsInfoVal,$trackCode,$otherValTmp['coupon_code'],$template_content);
                        if (!empty($template_replace_html)) {
                            $otherValTmp['cart_goods_info'] = $template_replace_html;
                        }
                    }
                    
                    // 浏览记录相关
                    if (file_exists(ROOT_PATH."/template/{$webName}_scan_template.php")) {
                        include_once(ROOT_PATH."/template/{$webName}_scan_template.php");
                        $template_replace_scan_html = $this->mergeScanHtml($mailAutoCreateListInfo,$goodsInfoVal,$trackCode,$otherValTmp['coupon_code'],$template_content);
                        if (!empty($template_replace_scan_html)) {
                            $otherValTmp['scan_goods_info'] = $template_replace_scan_html;
                        }
                    }
                  
                }
            }  elseif($mailAutoCreateListInfo['is_old'] == 3) {
                if(in_array($mailAutoCreateListInfo['site_id'],[12])) {  // gb crm中同步过来的相关数据
                    if ($mailAutoCreateListInfo['user_email_type'] == 11) { // 新版购物车相关
                        
                        if(isset($mailAutoCreateListInfo['lang']) && $mailAutoCreateListInfo['lang']) {
                            $lang = strtolower($mailAutoCreateListInfo['lang']);
                            if(file_exists(ROOT_PATH."/template/{$webName}_{$lang}_eocart_template.php")) {
                                include_once(ROOT_PATH."/template/{$webName}_{$lang}_eocart_template.php");
                                $templateEocartHtml = $this->mergeEoCartCookieHtml($mailAutoCreateListInfo,$goodsInfoVal,$trackCode,$templateContent);
                            
                                $otherValTmp['eocart_goods_info'] = $templateEocartHtml;
                            }
                            
                        } else if (file_exists(ROOT_PATH."/template/{$webName}_eocart_template.php")) {
                            include_once(ROOT_PATH."/template/{$webName}_eocart_template.php");
                           
                            $templateEocartHtml = $this->mergeEoCartCookieHtml($mailAutoCreateListInfo,$goodsInfoVal,$trackCode,$templateContent);
                            
                            $otherValTmp['eocart_goods_info'] = $templateEocartHtml;
                        }
                    } elseif($mailAutoCreateListInfo['user_email_type'] == 14) { // 新版浏览记录相关
                        if (!empty($goodsInfoVal['goods_list'])) {
                            $goodsInfoOther = json_decode($goodsInfoVal['goods_list'],true);
                            if (!empty($goodsInfoOther)) {
                                $goodsFirst = [];
                                $goodsOther = [];
                                 // 把一个商品挑选出来 (浏览商品 flag=1 如果没有则取第一个商品)
                                foreach ($goodsInfoOther as $key=>$goodsInfoOtherVal) {
                                    if (empty($goodsFirst) || $goodsInfoOtherVal['flag'] == 1) {
                                        $curKey = $key;
                                        $goodsFirst = $goodsInfoOtherVal; 
                                    } 
                                }
                                unset($goodsInfoOther[$curKey]);
                                if (!empty($goodsFirst['goods_link'])) {
                                    $goodsUrl1 = str_replace("http://" , "", $goodsFirst['goods_link']);
                                    $otherValTmp['goods_url1'] = str_replace("https://" , "", $goodsUrl1);
                                    $otherValTmp['goods_url1'] = strpos($otherValTmp['goods_url1'],'?') === false ? $otherValTmp['goods_url1'] . '?1&'.$trackCode : $otherValTmp['goods_url1'] . '&'.$trackCode;
                                } else {
                                    $otherValTmp['goods_url1'] = "";
                                }
                                if (!empty($goodsFirst['goods_picture'])) {
                                    $goodsImg1 = str_replace("http://" , "", $goodsFirst['goods_picture']);
                                    $otherValTmp['goods_img1'] = str_replace("https://" , "", $goodsImg1);
                                } else {
                                    $otherValTmp['goods_img1'] = "";
                                }
                                if (!empty($goodsFirst['good_title'])) {
                                    $otherValTmp['goods_title1'] = $goodsFirst['good_title'];
                                } else {
                                    $otherValTmp['goods_title1'] = "";
                                }
                                $i = 2; // 推荐商品只需要两个
                                foreach ($goodsInfoOther as $goodsInfoOtherVal) {
                                    if ($i > 3) {
                                        break;
                                    }
                                    if (!empty($goodsInfoOtherVal['goods_link'])) {
                                        $goodsUrl = str_replace("http://" , "", $goodsInfoOtherVal['goods_link']);
                                        $otherValTmp['goods_url'.$i] = str_replace("https://" , "", $goodsUrl);
                                        $otherValTmp['goods_url'.$i] = strpos($otherValTmp['goods_url'.$i],'?') === false ? $otherValTmp['goods_url'.$i] . '?1&'.$trackCode : $otherValTmp['goods_url'.$i] . '&'.$trackCode;
                                    } else {
                                        $otherValTmp['goods_url'.$i] = "";
                                    }
                                    
                                    if (!empty($goodsInfoOtherVal['goods_picture'])) {
                                        $goodsImg = str_replace("http://" , "", $goodsInfoOtherVal['goods_picture']);
                                        $otherValTmp['goods_img'.$i] = str_replace("https://" , "", $goodsImg);
                                    } else {
                                        $otherValTmp['goods_img'.$i] = "";
                                    }
                                    
                                    if (!empty($goodsInfoOtherVal['good_title'])) {
                                        $otherValTmp['goods_title'.$i] = $goodsInfoOtherVal['good_title'];
                                    } else {
                                        $otherValTmp['goods_title'.$i] = "";
                                    }
                                    $i++;
                                } 
                            }
                        }
                    }
                }
            }elseif ($mailAutoCreateListInfo['is_old'] == 2) { // 旧版后来改动的
                
                if (!empty($goodsInfoVal['goods_list'])) {
                    $goodsInfoOther = unserialize($goodsInfoVal['goods_list']);
//                    $goodsInfoOther = json_decode(stripslashes($goodsInfoVal['goods_list']),true);
                    
                    if (!empty($goodsInfoOther)) {
                        
                        // gb购物车邮件商品是不确定的这里要做兼容
                        if (file_exists(ROOT_PATH."/template/{$webName}_cart_template.php")) {
                            include_once(ROOT_PATH."/template/{$webName}_cart_template.php"); 
                        } 
                        $curKey = 1;
                        foreach ($goodsInfoOther as $goodsInfoK => $goodsInfoV) {
                            if (!empty($cartContentTpl)) { // gb每个商品都要绑定一个不同的cookie_code, 追加一个和商品绑定的cookie_code
                                $cookieCode = $this->rand_keys(16);
                                $goodsInfoOther[$goodsInfoK]['cookie_code'] = $cookieCode;
                                $otherValTmp['cart_goods_info'] .= $this->mergeCartCouponHtmlIndefinite($mailAutoCreateListInfo,$goodsInfoV,$trackCode,$otherValTmp['coupon_code'],$cartContentTpl,$cookieCode); 
                            }
                            
                            if (!empty($cartContentTplCommon)) { // 其他网站不需要每个商品绑定cookie_code,单独写
//                                $otherValTmp['cart_goods_info_common'] .=
//                                        $this->mergeCartCouponHtmlIndefiniteCommon($mailAutoCreateListInfo,$goodsInfoV,$trackCode,$otherValTmp['coupon_code'],$cartContentTplCommon); 
                                $otherValTmp['img_info_all'] .=
                                        $this->mergeCartCouponHtmlIndefiniteCommon($mailAutoCreateListInfo,$goodsInfoV,$trackCode,$otherValTmp['coupon_code'],$cartContentTplCommon['goods_img'],1); 
                                $otherValTmp['goods_name_info_all'] .=
                                        $this->mergeCartCouponHtmlIndefiniteCommon($mailAutoCreateListInfo,$goodsInfoV,$trackCode,$otherValTmp['coupon_code'],$cartContentTplCommon['goods_name'],2); 
                                $otherValTmp['price_info_all'] .=
                                        $this->mergeCartCouponHtmlIndefiniteCommon($mailAutoCreateListInfo,$goodsInfoV,$trackCode,$otherValTmp['coupon_code'],$cartContentTplCommon['price'],3); 
                            }
                            
                            
                            if (!empty($goodsInfoV['goods_url'])) {
                                $goodsInfoV['goods_url'] = str_replace("https://" , "", $goodsInfoV['goods_url']);
                                $otherValTmp['goods_url' . $curKey] = str_replace("http://","",$goodsInfoV['goods_url']);
                            }
                            
                            if (!empty($goodsInfoV['goods_img'])) {
                                $goodsInfoV['goods_img'] = str_replace("https://" , "", $goodsInfoV['goods_img']);
                                $otherValTmp['goods_img' . $curKey] = str_replace("http://","",$goodsInfoV['goods_img']);
                            }
                            
                            if (!empty($goodsInfoV['goods_name'])) {
                                $otherValTmp['goods_name' . $curKey] = $goodsInfoV['goods_name']; 
                            }
                            
                            if (!empty($goodsInfoV['goods_title'])) {
                                $otherValTmp['goods_title' . $curKey] = $goodsInfoV['goods_title'];
                            }
                            
                            if (!empty($goodsInfoV['shop_price'])) {
                                $otherValTmp['shop_price' . $curKey] = $goodsInfoV['shop_price'];
                            }
                            
                            if (!empty($goodsInfoV['market_price'])) {
                                $otherValTmp['market_price' . $curKey] = $goodsInfoV['market_price'];
                            }
                            $curKey++;
                        }
                    }
                } 
            }
            $otherValJson = json_encode($otherValTmp);
            $paramsBind = [':otherValJson' =>  $otherValJson];
            if (!empty($cartContentTpl)) {
                $paramsBind[':goodsList'] = serialize($goodsInfoOther);
                // 更新数据表中相关记录
                $updateSql = " update user_{$webName}_goods_data set coupon_code = '{$otherValTmp['coupon_code']}',cookie_code = '{$otherValTmp['cookie_code']}',other_vars= :otherValJson,goods_list=:goodsList,send_state=1,is_set_goods_cookie_code=1 where id = {$goodsInfoVal['id']}";
            } else {
                // 更新数据表中相关记录
                $updateSql = " update user_{$webName}_goods_data set coupon_code = '{$otherValTmp['coupon_code']}',cookie_code = '{$otherValTmp['cookie_code']}',other_vars= :otherValJson,send_state=1 where id = {$goodsInfoVal['id']}";
            }
            
            yii::$app->db->createCommand($updateSql)->bindValues($paramsBind)->execute(); 
        }
        
        // 更新记录表中的最后一次计划任务添加分组时间
        $curBjTime = \yii::$app->bjTime->time();
        $curDate = \yii::$app->bjTime->date('Y-m-d');
        $curDayStart = $curDayStart ? $curDayStart : \yii::$app->bjTime->strtotime($curDate." 00:00:00");
        $curAutoCreateSendTimeCurDay = $curDayStart + $mailAutoCreateListInfo['plan_send_time'];
        $updateSql = " update mail_auto_create set cron_curday_plan_add_group_time = {$curAutoCreateSendTimeCurDay} where id = " . $mailAutoCreateListInfo['id'];
        yii::$app->db->createCommand($updateSql)->execute();
        
        
    }
    
    /**
     * yumao
     * 2018-3-3
     * S、TD、TG营销邮件自动化应用方案添加分组
     */
    public function doAddGroupGoods($site,$whereStr,$lastSendGroupId=0,$groupType=0)
    {
        $data = [];
        $curBjTime = \yii::$app->bjTime->time();
        $siteInfo = Yii::$app->params['sites']['marketing_email']['web_config'][$site];
        $data['site_id'] = $siteInfo['site_id'];
        $templateIdArr = [
            'sammydress' => [
                'dev' => 447,
                'test' => 447,
                'product' => 1495,
            ],
            'trendsgal' => [
                'dev' => 469,
                'test' => 469,
                'product' => 1665,
            ],
            'twinkledeals' => [
                'dev' => 484,
                'test' => 484,
                'product' => 1666,
            ]
        ];
        $templateId = $templateIdArr[$site][YII_ENV];
        $data['template_id'] = $templateId;
        
        // 获取模版的相关信息
        $getTemplateIdSql = "select template_id,id,track_code from mail_template  where  is_use=1 and is_del=0 and status=1 and template_id = {$templateId}";
        $tempInfo = yii::$app->db->createCommand($getTemplateIdSql)->queryOne();
        $data['template_pk'] = $tempInfo['id'];
        
        // 查看有没有相关goods_data表中有相关的数据
        if ($groupType == 2) { // 分组2的用户直接发最新的数据
            $getGoodsInfoSql = "select id,goods_data from {$site}_goods_data order by id desc limit 1";
        } else {
            $getGoodsInfoSql = "select id,goods_data from {$site}_goods_data where is_send=0 order by id desc limit 1";
        }
        $goodsInfo = yii::$app->db->createCommand($getGoodsInfoSql)->queryOne();
        if (!empty($goodsInfo) && !empty($goodsInfo['goods_data'])) {
            $goodsInfoId = $goodsInfo['id'];
            $goodsInfo = json_decode($goodsInfo['goods_data'],true);
            if (!$goodsInfo) {
                $msg = "数据不是json格式";
                echo $msg;
                Elog::logCrontab($msg, 'doAddGroupGoods','exception'); // 记录信息到elog
                // 发送信息到消息中心
                // 发送错误消息
                $msgCenter = new MsgCenter();
                $msgCenter->sendSubgroupProductMessage($msg,$msg);  
                exit;
            } else {
               // $goodsInfoDealTemp = [];
                $goodsInfoDeal = [];
                $i = 1;
                foreach ($goodsInfo as $goodsOneInfo) {
                    foreach ($goodsOneInfo as $curKey=>$curVal) {
                        $goodsInfoDeal[$curKey.$i] = $curVal;
                    }
                    $i++;
                }
                $otherVals = $goodsInfoDeal;
                
                // 查一个模板标题
                $getEmailTitleSql = "select id,title_content from {$site}_email_title order by last_use_time asc limit 1";
                $emailTitleContent = yii::$app->db->createCommand($getEmailTitleSql)->queryOne();
                $otherVals['email_title'] = $emailTitleContent['title_content'];
                $data['other_vars'] = json_encode($otherVals);
            }
        } else {            
            $msg = "{$site}没有商品数据可以发送";
            echo $msg;
            Elog::logCrontab($msg, 'doAddGroupGoods','exception'); // 记录信息到elog
            // 发送信息到消息中心
            // 发送错误消息
            $msgCenter = new MsgCenter();
            $msgCenter->sendSubgroupProductMessage($msg,$msg);  
          
           exit;
        }
       
        // 跟踪码
        if ($tempInfo['track_code'])
        {
            $data['group_name'] = str_replace("{sendTime}", $curBjTime, $tempInfo['track_code']);
            $data['group_name'] = str_replace("{sendDate}", \yii::$app->bjTime->date('ymd',$curBjTime), $data['group_name']);
        }
        $data['utm_campaign'] = $data['group_name'];
        $data['send_mode'] = 2;
        $data['send_type'] = 0;
        $data['send_type_time'] = 0;
        $data['channel_id'] = 2;
        $data['sender'] = Yii::$app->params['sites']['marketing_email']['web_config'][$site]['api_email'];
        $data['state'] = 1;
        $data['start_time'] = $curBjTime;
        $data['boot_time'] = $curBjTime;
        $data['is_use_independent_ip'] = 0;
        $data['send_per_minute'] = 5000;
        $data['is_fix_time_send'] = 0;
        $data['track_code'] = "utm_source=mail_api&utm_medium=mail&utm_campaign=" .$data['utm_campaign'];
        $data['is_auto_group'] = 0; // 自动添加的分组
        // $tableName = "user_{$site}_goods_data";

        $groupModel = new MailGroup();
        $sendListModel = new MailSendlist();
        $statModel = new MailGroupEmailTypeStatistics();
        $trans = Yii::$app->db->beginTransaction();
        try {
            $groupId = $groupModel->addGroupGoods($data);
            
            // 把当前这条数据的is_send改成1
            $updateSql = "update {$site}_goods_data set is_send = 1 where id = {$goodsInfoId}";
            yii::$app->db->createCommand($updateSql)->execute();
            
            // 把当前标题的使用时间时间改成当前时间
            $updateEmailTitleSql = "update {$site}_email_title set last_use_time={$curBjTime} where id = {$emailTitleContent['id']}";
            yii::$app->db->createCommand($updateEmailTitleSql)->execute();
            
            // 把相关数据加入到队列中
            $count = $sendListModel->addSendListByWhereStr($data['site_id'], $groupId, $data['channel_id'],$data['template_pk'],$whereStr,$lastSendGroupId);
            if (0 == $count) {
                $groupModel->updateGroupByCondition(['group_id' => $groupId], ['is_del' => 1]);
            } else {
                $groupModel->updateGroupByCondition(['group_id' => $groupId], ['total_count' => $count]);
                $statModel->addMailStatItem($groupId, $data['site_id']);
                
                // 更新redis中相关数据
                
                // 更改goods_data表中数据的状态和添加一些附件变量值
               // $this->updateData($mailAutoCreateListInfo,$haveAddIdArr,$data['track_code']);
            }
            $trans->commit(); 
            if (0 == $count) {
                return false;
            } else {
                return $groupId;
            }
        } catch (\Exception $e) {
            $msg = "{$site}添加后期自动分组失败：".PHP_EOL.$e->getMessage().PHP_EOL.$e->getTraceAsString();
            $this->writeLog($msg);
            $trans->rollBack();
            echo  $msg;
            return false;
        }
        
    }
    /**
     * 添加分组
     */
    private function doAddGroup($mailAutoCreateListInfo,$userIdArr,$curDayStart=0)
    {
        $data = [];
        $webName = Yii::$app->params['sites']['marketing_email']['web_index'][$mailAutoCreateListInfo['site_id']];
        $curBjTime = \yii::$app->bjTime->time();
        // 获取模版的相关信息
        $getTemplateIdSql = "select template_id,id,track_code from mail_template  where  is_use=1 and is_del=0 and status=1 and template_id = {$mailAutoCreateListInfo['template_id']} and is_ab_test = 0";
        $tempInfo = yii::$app->db->createCommand($getTemplateIdSql)->queryOne();
        
        // 用户id信息进行处理
        $haveAddIdArr = [];
        if ($userIdArr) {
            foreach ($userIdArr as $userIdTemp) {
                $data['user_id'][] = $userIdTemp['user_id'];
                $haveAddIdArr[] =  $userIdTemp['id'];
            }
        }
        $data['site_id'] = $mailAutoCreateListInfo['site_id'];
       
        // 模版信息
        $data['template_id'] = $tempInfo['template_id'];
        $data['template_pk'] = $tempInfo['id'];
        
        // 跟踪码
        if ($tempInfo['track_code'])
        {
            $data['group_name'] = str_replace("{sendTime}", $curBjTime, $tempInfo['track_code']);
            $data['group_name'] = str_replace("{sendDate}", \yii::$app->bjTime->date('ymd',$curBjTime), $data['group_name']);
        }
        $data['utm_campaign'] = $data['group_name'];
        $data['send_mode'] = 2;
        $data['send_type'] = 0;
        $data['send_type_time'] = 0;
        $data['channel_id'] = 2;
        $data['sender'] = Yii::$app->params['sites']['marketing_email']['web_config'][$webName]['api_email'];
        $data['state'] = 1;
        $data['start_time'] = $curBjTime;
        $data['boot_time'] = $curBjTime;
        $data['is_use_independent_ip'] = 0;
        $data['send_per_minute'] = 5000;
        $data['is_fix_time_send'] = 0;
        $data['track_code'] = "utm_source=mail_api&utm_medium=mail&utm_campaign=" .$data['utm_campaign'];
        $data['is_auto_group'] = 1; // 自动添加的分组
        $groupModel = new MailGroup();
        $sendListModel = new MailSendlist();
        $statModel = new MailGroupEmailTypeStatistics();
        $trans = Yii::$app->db->beginTransaction();
        try {

            $groupId = $groupModel->addGroup($data);
            $count = $sendListModel->addMailAutoSendListByUserId($mailAutoCreateListInfo['site_id'], $groupId, $data['channel_id'],$data['template_pk'],$haveAddIdArr);
           
            if (0 == $count) {
                $groupModel->updateGroupByCondition(['group_id' => $groupId], ['is_del' => 1]);
            } else {
                $groupModel->updateGroupByCondition(['group_id' => $groupId], ['total_count' => $count]);
                $statModel->addMailStatItem($groupId, $data['site_id']);
                // 更改goods_data表中数据的状态和添加一些附件变量值
                $this->updateData($mailAutoCreateListInfo,$haveAddIdArr,$data['track_code'],$curDayStart);
            }
            $trans->commit();   
            echo "自动触发邮件id为{$mailAutoCreateListInfo['id']}添加分组成功\n";
        } catch (\Exception $e) {
            $msg = "自动触发邮件id为{$mailAutoCreateListInfo['id']}添加分组失败：".PHP_EOL.$e->getMessage().PHP_EOL.$e->getTraceAsString();
            $this->writeLog($msg);
////            var_dump($e->getMessage(),$e->getTraceAsString());
             $trans->rollBack();
             echo "自动触发邮件id为{$mailAutoCreateListInfo['id']}添加分组失败：系统繁忙，请稍后重试\n";
        }
    }
    
    /*
     * 记录相关日志
     */
    private function writeLog($msg)
    {
        $date = yii::$app->bjTime->date("Y-m-d H:i:s");
        $today = yii::$app->bjTime->date("Ymd");
        $dir = yii::$app->getRuntimePath() . "/logs/" . yii::$app->bjTime->date("Ym");
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        $filePath = $dir . "/add_group_{$today}.log";
        $msg = "[{$date}] $msg" . PHP_EOL;
        file_put_contents($filePath, $msg, FILE_APPEND);
    }
    /*
     * 检测网站是否在计划发送时间后一个小时之后生成分组，并将结果发送监控系统
     * liugang 20170831
     */
    public function actionCheckIsAddMailGroup()
    {
            set_time_limit(0);
            $mailAutoCreate = new MailAutoCreate();
            
            // 查询所有未删除的并且启动自动触发邮件任务
            $mailAutoCreateList = $mailAutoCreate->getAllAutoCreateListSuit();
            //取出所有配置的模板id
            $templateIds = $tempTrack = array();
            foreach($mailAutoCreateList as $list)
            {
                $templateIds[] = $list['template_id'];
            }
            
            if($templateIds)
            {
                $templateInfoArr =  yii::$app->db->createCommand("select template_id,id,track_code from mail_template where template_id in(".implode(',',$templateIds).") and is_use = 1 and is_del = 0 and status=1 and is_ab_test = 0")->queryAll();
                
                foreach($templateInfoArr as $templateInfo)
                {
                    $newTrackCode = '';
                    $trackCode = explode('_',$templateInfo['track_code']);
                    if(isset($trackCode[0]) && isset($trackCode[1]))
                    {
                        $newTrackCode = $trackCode[0].'_'.$trackCode[1];
                    }
                    $tempTrack[$templateInfo['template_id']] = $newTrackCode;
                }
                
            }
            
            $oldEmailType = array(
                1 => '购物车',
                2 => '热销',
                3 => '收藏夹',
                4 => '浏览记录'
            );
            $emailType = array(
                1 => '购物车',
                2 => '大码',
                3 => '复购类',
                4 => '品类'
            );
            //自检配置信息
            $selfCheckConfig = array(array(
                'plan_send_time'  => 0,
                'brief_code' =>'SELFCK_CART',
                'is_old'     => 1,
                'goods_type' => 1   
            ));
            $mailAutoCreateList = array_merge($mailAutoCreateList,$selfCheckConfig);
            
            foreach ($mailAutoCreateList as $key=>$webMailInfo) {
                
                if(isset($webMailInfo['brief_code']) && $webMailInfo['brief_code'] == 'SELFCK_CART')
                {
                    $webName = 'selfcheck';
                }
                else
                {
                    $webName = Yii::$app->params['sites']['marketing_email']['web_index'][$webMailInfo['site_id']];
                    
                }
                
                $curBjTime = \yii::$app->bjTime->time();
                $curDate = \yii::$app->bjTime->date('Y-m-d');
                $curDayStart = \yii::$app->bjTime->strtotime($curDate." 00:00:00");
                $data = [];
                $data['module_name'] = "marketing_email";
                // 各种邮件的处理
                // 查看是否到已经添加队列的时间
                $hours = $webName == 'selfcheck' ? 0 : 3600;
                
                if($webMailInfo['plan_send_time'] + $hours > 23*60*60) {
                    $curDayStart = $curDayStart - 24*60*60;
                }
                
                
                if ($curBjTime - $curDayStart >= $webMailInfo['plan_send_time'] + $hours) {  // 生成分组之后1个小时

                        //查看分组表中有没有生成分组
                        $whereArr = array(
                            'group_name' => ($webName == 'selfcheck' ? $webMailInfo['brief_code'] : $tempTrack[$webMailInfo['template_id']]),
                            'start_time' => $curDayStart + $webMailInfo['plan_send_time'],
                            'is_auto_group' => 1
                        );
                        $groupModel = new MailGroup();
                        if(!$groupModel->isExsitGroupByCondition($whereArr))
                        {
                            //不存在分组，判断是否有推送发送邮件数据
                             // 获取合适条件的用户数据
                            if ($webMailInfo['is_old'] == 1) { // 旧版相关数据

                                $email_type = array_key_exists($webMailInfo['goods_type'],$oldEmailType) ? $oldEmailType[$webMailInfo['goods_type']] : '';
                            } else if($webMailInfo['is_old'] == 2) {
                                $email_type = array_key_exists($webMailInfo['user_email_type'],$emailType) ? $emailType[$webMailInfo['user_email_type']] : '';
                            }else{
                                $email_type = array_key_exists($webMailInfo['user_email_type'],$emailType) ? $emailType[$webMailInfo['user_email_type']] : '';
                            }
                            if($webName == 'selfcheck')
                            {
                                $error = 'EMP营销邮件，自检网站推送数据为0，'.$email_type.'邮件未在 '.\yii::$app->bjTime->date('Y-m-d H:i:s',$curDayStart + $webMailInfo['plan_send_time']).' 生成发送分组';
                                \app\helpers\Monitor::reportCheckAddGroupError($error,1,1);
                                
                                $error = 'EMP营销邮件，自检网站推送数据不为0，'.$email_type.'邮件未在 '.\yii::$app->bjTime->date('Y-m-d H:i:s',$curDayStart + $webMailInfo['plan_send_time']).' 生成发送分组';
                                \app\helpers\Monitor::reportCheckAddGroupError($error,2,1);
                            }
                            else
                            {
                                $userIdArr = $this->getData($webMailInfo);


                                $haveAddIdArr = [];
                                if ($userIdArr) {
                                    foreach ($userIdArr as $userIdTemp) {
                                        $data['user_id'][] = $userIdTemp['user_id'];
                                        $haveAddIdArr[] =  $userIdTemp['id'];
                                    }
                                }
                                
                                if (isset($data['user_id']) && $data['user_id']) {//有推送发送邮件数据

                                    $error = 'EMP营销邮件，'.$webName.'网站推送数据不为0，'.$email_type.'邮件未在 '.\yii::$app->bjTime->date('Y-m-d H:i:s',$curDayStart + $webMailInfo['plan_send_time']).' 生成发送分组';
                                   
                                    \app\helpers\Monitor::reportCheckAddGroupError($error,2);

                                }else{//没有推送的要发送的邮件数据
                                    $error = 'EMP营销邮件，'.$webName.'网站推送数据为0，'.$email_type.'邮件未在 '.\yii::$app->bjTime->date('Y-m-d H:i:s',$curDayStart + $webMailInfo['plan_send_time']).' 生成发送分组';
                                    
                                    \app\helpers\Monitor::reportCheckAddGroupError($error,1);
                                }
                            }
                            
                        }
                        
                }

            }
            
    } 
}
